<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class GenerarTablas {

    var $CI;
    var $tables;
    var $sql;

    function GenerarTablas() {
        $this->CI = & get_instance();
        $this->CI->load->config('crud_config', true);
        $this->tables = $this->CI->config->item('tables', 'crud_config');
        $this->sql = $this->CI->config->item('crud_sql', 'crud_config');
    }

    function generacion_datos() {
        foreach ($this->sql as $sql_tabla) {
            $this->CI->db->query($sql_tabla);
        }

        $this->CI->db->empty_table($this->tables['tablas']);
        $this->CI->db->empty_table($this->tables['campos']);
        $tables = $this->CI->db->list_tables();
        foreach ($tables as $table) {
            $last_id = $this->_insert_tablas($table);
            $this->_insert_datos($table, $last_id);
        }
        $this->_crear_database_tables($tables);
    }
    
    function borrar_datos(){
        $this->CI->load->dbforge();
        foreach($this->tables as $tabla){
            $this->CI->dbforge->drop_table($tabla);
        }
    }

    private function _insert_tablas($p_tabla = null) {
        $this->CI->db->insert($this->tables['tablas'], array('nombre' => $p_tabla));
        return $this->CI->db->insert_id();
    }

    private function _insert_datos($p_tabla = null, $p_last_id = null) {
        $query = $this->CI->db->query("DESCRIBE " . $p_tabla);
        foreach ($query->result_array() as $columnas) {
            if ($columnas['Field'] != 'usumod' && $columnas['Field'] != 'usucre' && $columnas['Field'] != 'fecmod' && $columnas['Field'] != 'feccre') {
                $insertar = array();
                $insertar['nombre'] = $columnas['Field'];
                $insertar['visible_vista'] = '0';
                $insertar['visible_form'] = '0';
                $insertar['es_descripcion'] = '0';
                $insertar['fk_id_' . $this->tables['tablas']] = $p_last_id;
                $this->CI->db->insert($this->tables['campos'], $insertar);
            }
        }
    }
    
    private function _crear_database_tables($data = null){
        if($data != null){
            $cadena = "<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Database table settings
|--------------------------------------------------------------------------
|
| Table names
|
*/\n\n";
            foreach ($data as $table) {
                $cadena .= "\$config['dbtables']['".$table."'] = '".$table."';\n";
            }
            $this->CI->load->helper('file');
            write_file(APPPATH."/config/database_tables.php", $cadena);
        }
    }

}

?>